<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    button{
      position: fixed;
      right: 50px;
      bottom: 50px;
    }
  </style>
</head>

<body>
  <div id="app" style="height: 3000px">
    <input type="button" @click="hideShow" value="显示、消失"/>
    <home v-if="isShow"></home>
  </div>


  <script src="./vue.js"></script>
  <script>
    // 定义一个全局的指令
    Vue.directive('back-top', {
      inserted(el, binding){
        // 回到顶部初始化隐藏
        el.style.display="none";
        // 滚动条超出指定值 显示 否则隐藏
        window.onscroll = function(){
          // 获取滚动条滚动距离
          let sTop = document.documentElement.scrollTop||document.body.scrollTop;
          console.log(sTop);
          if(sTop > binding.value){
            el.style.display="block";
          }else{
            el.style.display="none";
          }
        }
        // 点击回到顶部
        el.onclick = function(){
          window.scrollTo(0,0)
        }
      },
      unbind(){
        console.log('指令与元素解绑');
        window.onscroll = null
      }
    })
    
    const Home = {
      template: `
        <div>
          <button v-back-top="100">回到顶部</button>
        </div>
      `
    }
    Vue.component('Home',Home)

    const vm = new Vue({
      el: '#app',
      data: {
        isShow: true
      },
      methods: {
        hideShow(){
          this.isShow = !this.isShow
        }
      }
    })
  </script>
</body>

</html>